package com.jky.filesystem.utils;

import ohos.app.Context;
import ohos.bundle.IBundleManager;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;

import java.util.ArrayList;
import java.util.List;

public class PermissionsUtils {
    private static final HiLogLabel LABEL_LOG = new HiLogLabel(3, 0xD001100, "测试");

    public static void requestRemotePermission(Context context) {
        String[] permissions = {
                "ohos.permission.DISTRIBUTED_DATASYNC"
        };
        requestPermission(context, permissions);
    }

    public static void requestFilePermission(Context context) {
        String[] permissions = {
                "ohos.permission.READ_USER_STORAGE",
                "ohos.permission.WRITE_USER_STORAGE",
        };
        requestPermission(context, permissions);
    }

    public static void requestAllPermission(Context context) {
        String[] permissions = {
                "ohos.permission.READ_USER_STORAGE",
                "ohos.permission.WRITE_USER_STORAGE",
                "ohos.permission.DISTRIBUTED_DATASYNC"
        };
        requestPermission(context, permissions);
    }

    private static void requestPermission(Context context,String[] permissions) {

        List<String> applyPermissions = new ArrayList<>();
        for (String element : permissions) {
            HiLog.info(LABEL_LOG, "检测权限: " + element);
            checkPermission(applyPermissions, element, context);
        }
        context.requestPermissionsFromUser(applyPermissions.toArray(new String[0]), 0);
    }

    private static void checkPermission(List<String> applyPermissions, String element, Context context) {
        if (context.verifySelfPermission(element) != IBundleManager.PERMISSION_GRANTED) {
            if (context.canRequestPermission(element)) {
                applyPermissions.add(element);
            } else {
                HiLog.info(LABEL_LOG, "用户已拒绝权限");
            }
        } else {
            HiLog.info(LABEL_LOG, "用户授予了权限：" + element);
        }
    }
}
